/**
 * 
 * Concurrent Programming
 * 
 * Exercise 1.1 
 * 
 * Conclusion
 * 
 * 
 * Where to put the delay?
 * Answer:
 * 			Put the delay of the first thread after reading counter but before the update.
 * Reason:
 * 			Reason for choosing thread 1:
 * 				 Thread 1 is called first then thread 2.
 * 			
 * 			How to set the delay:
 * 				 id = 1 and i = 1 and sleep the longer the better			
 * 
 * 			Reason for putting the delay after reading the counter:
 * 			     In the first iteration thread 1 reads the counter value of 0 to temp and then sleeps, while thread 2 is incrementing the counter.
 * 				 When thread 1 is revoked it will update the counter from temp and increase with 1 which means that counter= 1.
 * 				 If we let thread 1 sleep for a long time and thread 2 is finished then counter will have be set to the value of counter when thread 1
 * 				 is finished which will be 100000.
 * 
 * @author Sissi
 *
 */


class Counter implements Runnable {

  private int counter = 0;
  private final int rounds = 100000;

  public void run () {
    try {
      int id;
      String name = Thread.currentThread().getName();
      if (name.equals("thread1")) id = 1;
      else id = 2;
      for(int i = 0; i < rounds; i++) {
    	  Thread.currentThread().setName("Process "+id);
        // Delay here?
        int tmp = counter;
        // Perhaps here?
        if (id== 1 && i== 1) Thread.sleep(200);
        counter = tmp + 1;
        // Or here?
        //if (id== ?? && i== ??) Thread.sleep(??);
      }
    } catch (InterruptedException e) {
      System.out.println ("Interrupted!");
    }
  }

  public static void main (String[] args) {
    try {
      Counter c = new Counter ();

      // Create two threads that run our run () method.
      Thread t1 = new Thread (c, "thread1");
      Thread t2 = new Thread (c, "thread2");

      t1.start (); t2.start ();

      // Wait for the threads to finish.
      t1.join (); t2.join ();

      // Print the counter
      System.out.println(c.counter);

    } catch (InterruptedException e) {
      System.out.println ("Interrupted!");
    }
  }

}